import hashlib

from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect

from .models import Users


def addUser(request, user):
    try:
        Users.objects.get(username=user.username)
        return render(request, "pages/user/signup.html", {'failed': '用户名已存在'})
    except:
        user.save()
        rep = render(request, "pages/user/signup_success.html", {'name': user.username})
        rep.set_cookie('me', f'{user.username}^{user.password}')
        return rep


def verify(request, user):
    try:
        result = Users.objects.get(username=user.username)
        if result.password == user.password:
            rep = HttpResponseRedirect("/")
            rep.set_cookie('me', f'{result.username}^{result.password}')
            return rep
        else:
            return render(request, "pages/user/signin.html", {'failed': '用户名或密码错误'})
    except:
        return render(request, "pages/user/signin.html", {'failed': '此用户不存在'})


def getPwd(name):
    try:
        return Users.objects.get(username=name).password
    except:
        return


def changePwd(username, pwd1, pwd2):
    user = Users.objects.get(username=username)
    pwd1 = hashlib.md5((pwd1 + 'awesome_spider').encode()).hexdigest()
    if user.password == pwd1:
        user.password = hashlib.md5((pwd2 + 'awesome_spider').encode()).hexdigest()
        user.save()
        return {'result': True, 'detail': ''}
    else:
        return {'result': False, 'detail': '原密码错误'}
